"""
-------------------------------
|
|   返回系统信息的视图
|   系统时间，内存，cpu 网络api
------------------------------
|   王通
|   2019-6-26
------------------------------
"""
import psutil
import os, sys, subprocess, platform, datetime
import socket
from django.views.generic import View
from django.http import JsonResponse

IO_SENT = 0
IO_RECV = 0


class ResultMixin:
    @staticmethod
    def make_result(code=200, data=None, error=None):
        return {"code": code, "data": data, "error": error}


class GetSystemTimeView(ResultMixin, View):
    """
    获取系统时间,页面每次刷新请求一次
    """

    def get(self, request, **kwargs):
        # 先判断是linux 还是windows
        system = platform.system()
        if "windows" == system.lower():
            sys_time = datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
            data = {"system": system, "version": platform.version()}

        else:
            system, version, _ = platform.dist()
            data = {"system": system, "version": version}
            sys_time = self.get_runtime()
            data["sys_time"] = sys_time
        # 得到系统的启动时间

        return JsonResponse(self.make_result(data=data))

    @staticmethod
    def get_runtime():
        cmd_mess = r"cat /proc/uptime"
        rd = os.popen(cmd_mess).read().strip().split()[0]
        seconds = float(rd)
        days = int(seconds / 60 / 60 / 24)
        hours = int(seconds / 60 / 60 % 24)
        minutes = int(seconds / 60 % 60)
        str_run_time = "%d天%d小时%d分钟" % (days, hours, minutes)
        return str_run_time


class GetSystemInfoView(ResultMixin, View):
    """
    获取获取
    """

    def get(self, request, **kwargs):
        global IO_RECV, IO_SENT
        # 获取系统cpu 使用率
        cpu = psutil.cpu_percent(interval=0)
        # 获取ram 使用率
        ram = psutil.virtual_memory().percent
        # 获取硬盘用量
        used = psutil.disk_usage('/').used
        free = psutil.disk_usage("/").free
        # 获取网络流量,和当前时间
        now = datetime.datetime.now().strftime("%H:%M:%S")
        sent1 = psutil.net_io_counters().bytes_sent
        recv1 = psutil.net_io_counters().bytes_recv
        # os.system('cls')  # 执行清屏命令
        sent = sent1 - IO_SENT  # interval 秒内所获取的上传字节数
        recv = recv1 - IO_RECV  # interval 秒内所获取的下载字节数

        IO_SENT = sent1
        IO_RECV = recv1

        data = {"cpu": cpu, "ram": ram,
                "disk": {"disk_used": used, "disk_free": free},
                "io": {"time": now, "sent": sent, "recv": recv}
                }
        return JsonResponse(self.make_result(data=data))
